package com.hsylient.javase.chapter13;

import lombok.SneakyThrows;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Date;

public class ReflectField {

    @Test
    @SneakyThrows
    public void testReflectField() {
        Class<?> aClass = Class.forName("com.hsylient.javase.chapter13.Student");
        for (Field field : aClass.getDeclaredFields() ) {
            // 拿到成员变量信息封装的对象
            System.out.println(field);
            // 拿到成员变量的名称
            System.out.println(field.getName());
            // 拿到修饰符的代号，通过Modifier类来转码
            System.out.println(Modifier.toString(field.getModifiers()));
            // 拿到成员变量的类型
            System.out.println(field.getType());
        }

        Object instance = aClass.getDeclaredConstructor().newInstance();
        Field birthday = aClass.getDeclaredField("birthday");
        birthday.setAccessible(Boolean.TRUE);
        birthday.set(instance, new Date[]{new Date(), new Date(), new Date()});
        System.out.println(instance);
    }

    @Test
    @SneakyThrows
    public void testCompile() {
        Class<?> aClass = Class.forName("java.lang.String");
        System.out.println("package " + aClass.getPackageName() + ";");
        System.out.println();
        System.out.println(Modifier.toString(aClass.getModifiers()) + " " + aClass.getSimpleName() + " class {");

        for (Field declaredField : aClass.getDeclaredFields()) {
            String mod = Modifier.toString(declaredField.getModifiers());
            String typeName = declaredField.getType().getCanonicalName();
            String fieldName = declaredField.getName();
            System.out.println('\t' + mod + " " + typeName + " " + fieldName + ";");
        }

        for (Constructor<?> declaredConstructor : aClass.getDeclaredConstructors()) {
            System.out.print('\t' + Modifier.toString(declaredConstructor.getModifiers()) + " " + aClass.getSimpleName() + "(");
            for (int i = 0; i < declaredConstructor.getParameters().length; i++) {
                System.out.print(declaredConstructor.getParameters()[i].getType().getCanonicalName() + " " + declaredConstructor.getParameters()[i].getName());
                if (i != declaredConstructor.getParameters().length -1) {
                    System.out.print(",");
                } else {
                    System.out.print(");");
                }
            }
            System.out.println();
        }
        System.out.println("}");
    }
}
